package com;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.InetSocketAddress;

public class SendServer implements Runnable {
    private EventLoopGroup mainGroup;
    private EventLoopGroup subGroup;
    private ServerBootstrap server;
    private TextHandler textHandler;
    private EchoClientHandler handler;
    private int port;

    public SendServer(EchoClientHandler handler, int port) throws Exception {
        mainGroup = new NioEventLoopGroup();
        subGroup = new NioEventLoopGroup();
        textHandler = new TextHandler();
        this.handler = handler;
        this.port = port;

        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(this.port)) //6.设置socket地址使用所选端口
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();

                        pipeline.addLast(new HttpServerCodec());

                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 64));

                        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                        pipeline.addLast(textHandler);
                    }
                });
    }

    @Override
    public void run() {
        try {
            ChannelFuture future = server.bind().sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }

    @ChannelHandler.Sharable
    private class TextHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

        @Override
        protected void channelRead0(ChannelHandlerContext cxt, TextWebSocketFrame msg) throws Exception {
        }

        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            handler.addChannel(ctx.channel());
        }

        @Override
        public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
            System.out.println("客户端断开，channel对应的长id为：" + ctx.channel().id().asLongText());
            System.out.println("客户端断开，channel对应的短id为：" + ctx.channel().id().asShortText());
        }
    }

}
